// AppUpgrade.js - UniApp在线升级模块
import config from '@/config'
import {postAction} from "./action";

class AppUpgrade {
    /**
     * 初始化升级管理器
     * @param {Object} options - 配置选项
     * @param {string} options.apiUrl - 版本检测API地址
     * @param {string} options.downloadPath - 文件下载目录
     * @param {boolean} options.debugMode - 调试模式开关
     */
    constructor(options = {}) {
        this.apiUrl = options.apiUrl || '';
        this.downloadPath = options.downloadPath || '_downloads/';
        this.debugMode = options.debugMode || false;
        this.currentVersion = '';
        this.task = null;
        this.checkTimeout = null;
    }

    /**
     * 初始化应用版本信息
     */
    upgrade_init() {
        return new Promise((resolve, reject) => {
            const appid = plus.runtime.appid;
            plus.runtime.getProperty(appid, (widgetInfo) => {
                this.currentVersion = widgetInfo.version;
                this.debugLog('当前版本:', this.currentVersion);
                resolve(widgetInfo);
            }, reject);
        });
    }

    /**
     * 检查版本更新
     * @returns {Promise<Object>} 更新信息
     */
    async checkVersion() {
        try {
            const widgetInfo = await this.upgrade_init();

            const res = await postAction(this.apiUrl);
            if (!res.success) {
                throw new Error(res.message);
            }

            const data = res.result;
            const updateInfo = {
                hasUpdate: false,
                newVersion: '',
                description: '',
                downloadUrl: '',
                isForce: false,
                packageType: 'apk' // apk/ipa/wgt
            };
            if (!data || !data.version) return updateInfo;
            // 比较版本号
            if (this.compareVersions(data.version, widgetInfo.version) > 0) {
                updateInfo.hasUpdate = true;
                updateInfo.newVersion = data.version;
                updateInfo.description = data.description || '发现新版本';
                updateInfo.downloadUrl = data.downloadUrl;
                updateInfo.isForce = !!data.force;
                updateInfo.packageType = data.packageType || 'apk';
            }

            return updateInfo;
        } catch (error) {
            this.debugLog('版本检测失败:', error);
            return {hasUpdate: false, error};
        }
    }

    /**
     * 版本号比较
     * @param {string} v1 - 版本1
     * @param {string} v2 - 版本2
     * @returns {number} 比较结果 (1: v1 > v2, -1: v1 < v2, 0: 相等)
     */
    compareVersions(v1, v2) {
        const v1Parts = v1.split('.').map(part => {
            const match = part.match(/\d+/);
            return match ? parseInt(match[0]) : 0;
        });

        const v2Parts = v2.split('.').map(part => {
            const match = part.match(/\d+/);
            return match ? parseInt(match[0]) : 0;
        });

        for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
            const num1 = i < v1Parts.length ? v1Parts[i] : 0;
            const num2 = i < v2Parts.length ? v2Parts[i] : 0;

            if (num1 > num2) return 1;
            if (num1 < num2) return -1;
        }

        return 0;
    }

    /**
     * 开始下载更新包
     * @param {string} url - 下载URL
     * @param {Function} progressCallback - 进度回调
     * @returns {Promise<Object>} 下载任务信息
     */
    download(url, progressCallback) {
        return new Promise((resolve, reject) => {
            const filename = this.getFilename(url);

            // 检查文件是否已存在
            if (this.fileExists(filename)) {
                resolve({path: filename, size: this.getFileSize(filename)});
                return;
            }

            this.debugLog('开始下载:', url);

            const downloadTask = uni.downloadFile({
                url: url,
                success: (res) => {
                    if (res.statusCode === 200) {
                        progressCallback(100);
                        console.log("下载成功，临时路径:", res.tempFilePath);
                        resolve({path: res.tempFilePath});
                    }
                },
                fail: (err) =>  reject(new Error(`下载失败，状态码: ${err}`))
            });

            // 核心：监听进度回调
            downloadTask.onProgressUpdate((res) => {
                const progress = res.progress; // 0-100的整数百分比
                console.log(`进度: ${progress}%`);
                progressCallback(progress);
            });

        });
    }

    /**
     * 安装更新包
     * @param {string} filePath - 文件路径
     * @param {string} packageType - 包类型 (apk/wgt)
     * @returns {Promise<void>}
     */
    install(filePath, packageType = 'apk') {
        return new Promise((resolve, reject) => {
            if (packageType === 'wgt') {
                // 热更新安装
                plus.runtime.install(filePath, {
                    force: false
                }, () => {
                    this.debugLog('热更新安装成功');
                    resolve();
                }, (error) => {
                    this.debugLog('热更新安装失败:', error);
                    reject(new Error(`热更新安装失败: ${error.message}`));
                });
            } else {
                // 整包安装
                plus.runtime.install(filePath, {
                    force: false
                }, () => {
                    this.debugLog('应用安装成功');
                    resolve();
                }, (error) => {
                    this.debugLog('应用安装失败:', error);
                    reject(new Error(`应用安装失败: ${error.message}`));
                });
            }
        });
    }

    /**
     * 重启应用
     */
    restartApp() {
        plus.runtime.restart();
    }

    /**
     * 跳转App Store（iOS应用更新）
     * @param {string} appId - App Store应用ID
     */
    openAppStore(appId) {
        if (uni.getSystemInfoSync().platform === 'ios') {
            plus.runtime.openURL(`itms-apps://itunes.apple.com/app/id${appId}`);
        }
    }

    /**
     * 检查文件是否存在
     * @private
     */
    fileExists(path) {
        try {
            return !!plus.io.getFileInfoSync(path);
        } catch (e) {
            return false;
        }
    }

    /**
     * 获取文件大小
     * @private
     */
    getFileSize(path) {
        try {
            const info = plus.io.getFileInfoSync(path);
            return info.size || 0;
        } catch (e) {
            return 0;
        }
    }

    /**
     * 从URL获取文件名
     * @private
     */
    getFilename(url) {
        const parts = url.split('/');
        return parts[parts.length - 1];
    }

    /**
     * 调试日志
     * @private
     */
    debugLog(...args) {
        if (this.debugMode) {
            console.log('[AppUpgrade]', ...args);
        }
    }
}

// 导出单例实例
const appUpgrade = new AppUpgrade({
    apiUrl: "/defaultManage/checkBossVersion",
    debugMode: true
});

export default appUpgrade;

// 使用方法示例（在App.vue中）:
// import appUpgrade from '@/common/AppUpgrade.js';
//
// onLaunch() {
//   // #ifdef APP-PLUS
//   appUpgrade.checkVersion().then((updateInfo) => {
//     if (updateInfo.hasUpdate) {
//       // 显示更新对话框
//       uni.navigateTo({
//         url: '/pages/upgrade?force=' + updateInfo.isForce
//               + '&url=' + encodeURIComponent(updateInfo.downloadUrl)
//               + '&desc=' + updateInfo.description
//               + '&type=' + updateInfo.packageType
//       });
//     }
//   });
//   // #endif
// }
